package com.jasiri.project.ui.launch

import android.annotation.SuppressLint
import android.view.View
import com.jasiri.project.analysis.TestAnalysisInit
import com.jasiri.project.databinding.ActivityLaunchBinding
import com.jasiri.project.pro.ProActivity
import com.jasiri.project.ui.credit.activity.CreditActivity
import com.jasiri.project.ui.user.activity.UserLoginActivity
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.helper.ActivityStackHelper
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.HttpDns
import com.jasiri.project.utils.http.IHttpCallback
import org.json.JSONObject
import java.util.TimeZone

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/21 16:12
 * @Annotation：启动页
 */
@SuppressLint("CustomSplashScreen")
class LaunchActivity: ProActivity() {

    private lateinit var binding: ActivityLaunchBinding

    override fun getRootView(): View {
        binding = ActivityLaunchBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        isNeedHideLoading = false
        //关闭所有页面
        ActivityStackHelper.finishAllActivity(LaunchActivity::class.java)
    }

    override fun initListener() {

    }

    override fun initData() {
        showLoading()
        testDNSIpResolver()
//        loadTimeZoneAction()
    }

    /**
     * 进入登录
     */
    fun enterLoginPage() {
        onIntent(UserLoginActivity::class.java)
        finish()
    }

    /**
     * 进入主页
     */
    fun enterMainPage() {
        //保存过时区 && 时区不相同 需要重新登录
        val saveZoneId = Configs.getSPString(Configs.SPKEY.JASIRI_TIMEZONE_ID)
        if (saveZoneId.isNotEmpty() && saveZoneId != TimeZone.getDefault().id){
            enterLoginPage()
            return
        }
        onIntent(CreditActivity::class.java)
        finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_LAUNCH_END,"")
    }

    /**
     * 获取地区转发
     * Timezone
     */
    private fun loadTimeZoneAction(){
        val params = JSONObject().apply {
            put("p",Configs.AppName)
            put("tz", TimeZone.getDefault().id)
        }
        val httpUrl = AppUrls.APP_URL + AppUrls.URL.TIMEZONE
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val dataString = data.optString("data")
                var timeZone = ""
                var zoneCode = ""
                var zoneCountry = ""

                dataString.split(",").apply {
                    if (this.isNotEmpty()){
                        timeZone = this[0].trim()
                    }
                    if (this.size >= 2){
                        zoneCode = this[1].trim()
                    }
                    if (this.size >= 3){
                        zoneCountry = this[2].trim()
                    }
                }
                //保存转发地区
                Configs.saveSPString(Configs.SPKEY.JASIRI_TIMEZONE,timeZone)
                //保存转发地区 区号
                Configs.saveSPString(Configs.SPKEY.JASIRI_TIMEZONE_CODE,zoneCode)
                //保存国家标识
                Configs.saveSPString(Configs.SPKEY.JASIRI_TIMEZONE_COUNTRY,zoneCountry)
                //初始化analysis lib 赋值 转发地区
                TestAnalysisInit.initAnalysisLibAtZoneSuccess()
                addEvent(EventType.PAGE.PAGE_LAUNCH_START,"")

                loadConfigAction()
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }

        })
    }

    /**
     * 获取APP配置信息
     */
    private fun loadConfigAction(){
        val params = JSONObject().apply {
            put("product",Configs.AppName)
            put("path",AppUrls.PATH.APP_INFO)
        }
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                hideLoading()
                val obj = data.optJSONObject("obj")
                //保存所有数据
                if (obj != null) {
                    Configs.saveSPString(Configs.SPKEY.JASIRI_COMMON,obj.toString())
                }
                // TODO: 2025-04-23 提高转化率需求1，直接进入登录或主页
                //已登录 - 进入主页
                if (Configs.getSPBoolean(Configs.SPKEY.JASIRI_LOGIN)){
                    //初始化analysis lib 赋值 用户id 和 token
                    TestAnalysisInit.initAnalysisLibAtLoginSuccess()
                    enterMainPage()
                } else {//进入登录页
                    enterLoginPage()
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideLoading()
            }
        })
    }

    // 测试ip解析
    private fun testDNSIpResolver() {
        try {
            HttpDns().lookupSys(AppUrls.APP_URL) { ipAddr ->
                AppUrls.APP_URL = "https://$ipAddr"
                loadTimeZoneAction()
            }
        } catch (e: Exception){
            e.printStackTrace()
        }
    }
}